package javanet.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.betwixt.expression.Context;
import org.apache.commons.betwixt.strategy.DefaultObjectStringConverter;

/**
 * @author Markus Holzer
 */
public class JavaNETObjectStringConverter extends DefaultObjectStringConverter {

	private static final long serialVersionUID = 3423742708157699902L;

	private static DateFormat DATE_FORMAT = new SimpleDateFormat(
			"yyyy-MM-dd'T'HH:mm:ss");

	@Override
	public String objectToString(Object object, @SuppressWarnings("rawtypes") Class type, Context context) {
		try {
			if (type == Date.class)
				return DATE_FORMAT.format(object);
			else
				return super.objectToString(object, type, context);
		} catch (Exception e) {
			return "";
		}
	}

	@Override
	public Object stringToObject(String value, @SuppressWarnings("rawtypes") Class type, Context context) {
		try {
			if (type == Date.class)
				return DATE_FORMAT.parse(value);
			else
				return super.stringToObject(value, type, context);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	protected void handleException(Exception e) {
		super.handleException(e);
	}
}
